import { mapState } from 'vuex'
import dly from '@/components/release.vue'

export default {
  components: {
    dly,
  },
  data() {
    return {
      hasNotchInScreen: false, //是否为刘海屏
      loading: true, // 是否显示骨架屏组件
      // 搜索框
      value: '',
      shape: 'round',
      clearabled: true,
      showAction: true,
      inputAlign: 'left',

      uid: '',
      uname: '',
      uavatar: '',
      noticeTime: '',
      noticeNum: 0,
      noticeMsg: '暂无通知',
      btnWidth: 138,
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#EB5C02',
          },
        },
      ],
      Nodatali: false, //没有数据
      userAddConversationList: [],
      userList: [],
      friendList: [],
      showimg: true,
      fabushow: false,
      // today: '',
      // yesterday: '',
      showEmty: false,
      pageLoading: false, //初始化加载效果
    }
  },
  computed: {
    ...mapState({
      isLogin: (state) => state.news.isLogin,
      isSDKReady: (state) => state.news.isSDKReady,
      conversationList: (state) => state.news.conversationList,
    }),
  },
  watch: {
    // isSDKReady(val) {
    //   //isSDKReady == true 请求会话列表
    //   if (val) {
    //     this.getConversationList()
    //   } else {
    //     this.loginTim()
    //   }
    // },
    conversationList(val) {
      this.getUserInfo(val)
    },
  },
  onLoad() {
    // #ifdef APP-PLUS
    this.hasNotchInScreen = plus.navigator.hasNotchInScreen()
    // #endif
    // this.today = this.dateFormat(new Date())
    // this.yesterday = this.dateFormat(new Date(new Date().getTime() - (24*60*60*1000)))
    this.$nextTick(() => {
      this.pageLoading = true
    })
  },
  onShow() {
    this.getTotal()
    if (this.isSDKReady) {
      this.getConversationList()
    } else {
      console.log(78)
      this.getTimInfo()
    }
  },
  methods: {
    //未读消息数量
    getTotal() {
      this.$api.news.getTotal().then((res) => {
        this.noticeNum = res.data.count
        this.noticeMsg = res.data.msg
        this.noticeTime = res.data.time
      })
    },

    //获取tim用户信息
    getTimInfo() {
      uni.showLoading({
        title: '加载中',
      })
      this.$api.news
        .getTimInfo({
          storeId: this.$store.state.userInfoDetail.store.storeId,
        })
        .then((res) => {
          console.log(res)
          this.$store.commit('news/setUer', {
            userId: res.data.userid,
            user:
              res.data.username !== null
                ? res.data.username
                : this.$store.state.userInfoDetail.store.storeName,
            img: res.data.img,
            userSig: res.data.usersig,
          })
          this.loginTim(res.data)
        })
        .catch((err) => {
          uni.hideLoading()
          console.log(err)
        })
    },

    loginTim(data) {
      this.tim
        .login({
          userID: data.userid,
          userSig: data.usersig,
        })
        .then((result) => {
          //登录成功后 更新登录状态
          console.log('登录tim')
          this.$store.commit('news/toggleIsLogin', true)
          setTimeout(() => {
            uni.hideLoading()
            this.getConversationList()
          }, 500)
        })
        .catch((err) => {
          uni.hideLoading()
          console.warn('login error:', err) // 登录失败的相关信息
        })
    },

    fabuclick() {
      this.fabushow = true
    },
    guanbi() {
      this.fabushow = true
    },
    //业务通知
    Businessnoticeclick() {
      uni.navigateTo({
        url: '/pages_news/businessNotice/businessNotice',
      })
    },
    //客服
    kefu() {
      uni.makePhoneCall({
        phoneNumber: this.$store.state.user.servicePhone + '',
      })
    },
    //聊天的节点加上外层的div
    nodesFliter(str) {
      let nodeStr =
        '<div style="align-items: center;word-wrap:break-word;">' +
        str +
        '</div>'
      return nodeStr
    },
    //获取消息列表
    getConversationList() {
      // 拉取会话列表
      let promise = this.tim.getConversationList()
      promise
        .then((res) => {
          let conversationList = res.data.conversationList // 会话列表，用该列表覆盖原有的会话列表
          if (conversationList.length) {
            //将返回的会话列表拼接上 用户的基本资料
            //说明：如果已经将用户信息 提交到tim服务端了 就不需要再次拼接
            this.$store.commit('news/updateConversationList', conversationList)
            this.friendList = []
            for (let i = 0; i < conversationList.length; i++) {
              this.friendList.push({
                user: conversationList[i].userProfile.nick,
                img: conversationList[i].userProfile.avatar,
                userId: conversationList[i].userProfile.userID,
                lastTime: conversationList[i].lastMessage.lastTime,
                unreadCount: conversationList[i].unreadCount,
                conversationID: conversationList[i].conversationID,
                messageForShow: conversationList[i].lastMessage.messageForShow,
              })
            }
          } else {
            this.showEmty = true
          }
        })
        .catch((err) => {
          console.warn('getConversationList error:', err) // 获取会话列表失败的相关信息
        })
    },

    //根据消息列表请求聊天对象的用户信息 并完成数据拼接
    getUserInfo(conversationList) {
      this.userAddConversationList = []
      conversationList.forEach((item) => {
        let obj = {}
        obj.conversation = item
        this.friendList.forEach((item1) => {
          if (item.toAccount === item1.userId) {
            obj.user = item1
          }
        })
        this.userAddConversationList.push(JSON.parse(JSON.stringify(obj)))
      })
    },

    toRoom(item) {
      this.$store.commit('news/updateConversationActive', item)
      uni.navigateTo({
        url:
          '/pages_news/room/room?img=' +
          item.user.img +
          '&user=' +
          item.user.user,
      })
    },
    //选择用户聊天
    checkUserToRoom(toUserInfo) {
      this.$store.commit('news/createConversationActive', toUserInfo)
      uni.navigateTo({
        url: '/pages_news/room/room?user=' + toUserInfo.user,
      })
    },

    //滑动删除等
    click(index, index1) {
      if (index1 === 0) {
        // this.listts.splice(index, 1);
        this.userAddConversationList.splice(index, 1)

        let promise = this.tim.getConversationList()
        promise
          .then((res) => {
            let conversationList = res.data.conversationList // 会话列表，用该列表覆盖原有的会话列表
            if (conversationList.length) {
              //将返回的会话列表拼接上 用户的基本资料
              //说明：如果已经将用户信息 提交到tim服务端了 就不需要再次拼接
              this.$store.commit(
                'updateConversationList',
                this.userAddConversationList
              )
            }
          })
          .catch((err) => {
            console.warn('getConversationList error:', err) // 获取会话列表失败的相关信息
          })
        this.$u.toast(`删除了第${index}个cell`)
      }
    },
    open(index) {
      this.listts[index].show = true
      this.listts.map((val, idx) => {
        if (index !== idx) this.listts[idx].show = false
      })
    },
    close(index) {
      this.listts[index].show = false
    },
    contentClick(index) {
      // console.log(index);
    },
    //菜单栏跳转
    menuclick(type) {
      if (type === 0) {
        uni.redirectTo({
          url: '/pages/index/index',
        })
      } else if (type === 1) {
        uni.redirectTo({
          url: '/pages/release/release',
        })
      } else if (type === 2) {
        uni.redirectTo({
          url: '/pages/news/news',
        })
      } else if (type === 3) {
        uni.redirectTo({
          url: '/pages/me/me',
        })
      }
    },
    //搜索框
    change1(value) {
      // 输入框内容发生变化时触发，会触发此事件，value值为输入框的内容
      //console.log(value);
    },
    custom(value) {
      //	用户点击右侧控件时触发
      //console.log(value);
      this.$u.toast('输入值为：' + value)
    },
    search(value) {
      //	用户确定搜索时触发，用户按回车键，或者手机键盘右下角的"搜索"键时触发
      this.$refs.uToast.show({
        title: '搜索内容为：' + value,
        type: 'success',
      })
    },
  },
}
